package com.example.myapplication.list

import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.example.myapplication.TestResult
import com.hades.common.vm.ListViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import org.hades.corelib.base.data.ResultData
import org.hades.corelib.base.extend.doLaunch
import javax.inject.Inject

@HiltViewModel
class TestListViewModel @Inject constructor(
    private val testUseCase: TestListUseCase
): ListViewModel() {
    // 可以直接使用Channel，LiveData、StateFlow都可以，Channel是冷流，需要注意重发问题
    private var ui: MutableStateFlow<ResultData<List<TestResult>>> = MutableStateFlow(ResultData.Loading)
    var uiFlow: StateFlow<ResultData<List<TestResult>>> = ui.asStateFlow()

    // 不想用ResultData包裹，需要drop默认值
    private var ui2: MutableStateFlow<List<TestResult>> = MutableStateFlow(emptyList())
    var uiFlow2: StateFlow<List<TestResult>> = ui2.asStateFlow()

    override fun requestData(page: Int) {
        // 使用密封类包装发送
        doLaunch {
            testUseCase.invoke(TestListUseCase.Params("参数"))
                .onEach {
                    ui.emit(ResultData.Success(it))
                }
                .composeState { e: Exception -> ui.emit(ResultData.Error(e)) }
                .launchIn(viewModelScope)
        }

        // 直接发送数据
        doLaunch {
            testUseCase.invoke(TestListUseCase.Params("参数"))
                .map {
                    ui2.emit(it)
                    it
                }
                .composeNomal()
                .launchIn(this)
        }

    }
}


